#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "Menu.h"
#include "Logic.h"

#include "../Graphic/Graphic.h"
#include "../Graphic/Input.h"

struct sMenu *Menu;
int Menu_Amount = 0;
int Menu_Max = 64;

void Menu_Init() {
    /* Speicher resavieren */
    Menu_Amount = 1;
    Menu = calloc(1, sizeof(struct sMenu));
    Menu[0].Visible = 0;
}


void Menu_Create(int X, int Y, bool Fixed, int Data, int (*iFunction)(int Data), int (*iGraphic)(int X, int Y, char *Text, int Data)) {
    int iN, iN_Free;
    iN_Free = -1;

    /* Freien Platz gesucht */
    for(iN = 0; iN < Menu_Max; iN++) {
        /* Fall überlauft neuer Speicher resavieren */
        if( iN >= Menu_Amount) {
            /* Nun mehr Platz */
            Menu_Amount++;
            /* Resavieren */
            Menu = realloc( Menu, Menu_Amount*sizeof(struct sMenu));
            if( Menu == NULL ) {
                logError("Kein virtueller RAM mehr vorhanden! ");
            }
            /* Reseten */
            Menu_Delete(iN);
        }
        /* Vorhandene Menüs überspringen */
        if(Menu[iN].Visible) continue;
        /* Gefunden */
        iN_Free = iN;
        break;
    }
    /* Fehler -> konnte menu nicht erstellen */
    if(iN_Free == -1)
        return;
    /* Werte eintragen */
    Menu[iN_Free].X = X;
    Menu[iN_Free].Y = Y;
    Menu[iN_Free].Fixed = Fixed;
    Menu[iN_Free].Data = Data;
    Menu[iN_Free].Function = iFunction;
    Menu[iN_Free].Graphic = iGraphic;
    Menu[iN_Free].Visible = 1;
}

void Menu_Graphic() {
    int i, X, Y;

    for(i = 0; i < Menu_Amount; i++)
    {
        /* Tote überspringen */
        if(!Menu[i].Visible) continue;
        X = Menu[i].X;
        Y = Menu[i].Y;
        /* Process durchführen */
        if(Menu[i].Graphic( X, Y, Menu[i].Text, Menu[i].Data))
            Menu_Delete(i);
    }
    return;
}

void Menu_Process() {
    int i, X, Y;

    /* jedes Item durcharbeiten */
    for(i = 0; i < Menu_Amount; i++)
    {
        /* Tote überspringen */
        if(!Menu[i].Visible) continue;
        /* Vereinfachert mir das Schreiben */
        X = Menu[i].X - Graphic_GetCamera(0);
        Y = Menu[i].Y - Graphic_GetCamera(1);
        /* Fixed -> HUD */
        if(Menu[i].Fixed) {
            X += Graphic_GetCamera(0);
            Y += Graphic_GetCamera(1);
        }
        /* Falls jemand auf das Item geklickt hat -> funktion aufrufen */
        if(Graphic_Distance( X, Y, Input.X, Input.Y) < 16  && Input.Mouse_1) {
            Input.Mouse_1 = 0;
            if(Menu[i].Function(Menu[i].Data))
                Menu_Delete(i);
        }
    }
}

void Menu_Delete(int i) {
    Menu[i].Visible = 0;
    Menu[i].X = 0;
    Menu[i].Y = 0;
    Menu[i].Fixed = 0;
}
